<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './message.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { createMessage as createMessageInfo, updateMessage } from '/@/api/opms/message';
  import { useMessage } from '/@/hooks/web/useMessage';
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const { createMessage } = useMessage();

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });
  const getTitle = computed(() => (!unref(isUpdate) ? '新增消息通知' : '编辑消息通知'));
  async function handleSubmit() {
    try {
      const values = await validate();
      //处理日期格式 如果后台日期对象为LocalDate 转换后的为 YYYY-MM-DD ，但是前端的日期选择器是 YYYY-MM-DD hh:mm:ss,需要转换一下
      setDrawerProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        await updateMessage(values);
        createMessage.success('更新成功');
      } else {
        await createMessageInfo(values);
        createMessage.success('创建成功');
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<script lang="ts">
  export default { name: 'MessageDrawer' };
</script>
